import { Button, Toast } from '@douyinfe/semi-ui'
import React, { useEffect, useState } from 'react'
// @ts-ignore
import { ipcApiRoute } from '@/api/main';
// @ts-ignore
import { ipc } from '@/utils/ipcRenderer';
import styles from './index.module.scss'
import useIpcRenderer from '../../Hook/useIpcRenderer';
const PythonRun = (props: any) => {
    const { setIsRunning } = props
    // 是否正在运行
    const [isRun, setIsRun] = React.useState(true)
    const [runlog, setRunlog] = React.useState('')

    // 定义一个函数来获取日志数据
    const fetchLogData = async (type: string) => {
        ipc.invoke(ipcApiRoute.pythonlog, {
            fileName: '/Midjunery/Mid-draw/dist/runlog.log', type, params: {}
        }).then((result: any) => {
            if (result) {
                setRunlog(result.message)
            }
        })
    };
    
    useEffect(() => {
        // 立即获取一次日志数据
        fetchLogData('get');

        // 设置定时器，每隔一定时间获取日志数据
        const intervalId = setInterval(() => {
            fetchLogData('get');
        }, 1000); // 每5秒更新一次

        // 清理函数：组件卸载时清除定时器
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div className={styles.PythonRun}>
            <div className={styles.option}>
                <span>正在运行的Python文件：</span>
                <Button type="primary" disabled={isRun} onClick={() => (
                    fetchLogData('delete'),
                    setIsRunning({
                        isRunning: false, type: ''
                    })
                )}>返回配置页面</Button>
                <Button type='danger' disabled={!isRun} onClick={() => {
                    setIsRun(false)
                    ipc.invoke(ipcApiRoute.pythonOperation, {
                        fileName: '/Midjunery/Mid-draw/dist/update.exe', type: "stop", params: {}
                    }).then((result: any) => {
                        if (result.result) {
                            Toast.success(result.message)
                        } else {
                            Toast.error(result.message)
                        }
                    })
                }}>点击终止运行</Button>
            </div>
                <pre  className={styles.runLog}>{runlog}</pre>
        </div>
    )
}

export default PythonRun